package ai4games_tests.soccer;

import game2dai.World;
import game2dai.entities.BaseEntity;
import game2dai.fsm.Dispatcher;
import game2dai.fsm.State;
import game2dai.fsm.Telegram;
import game2dai.maths.Vector2D;

public class PlayerGlobal extends State implements Constants {

	private static PlayerGlobal instance = null;

	public static PlayerGlobal state(){
		if(instance == null)
			instance = new PlayerGlobal();
		return instance;
	}

	@Override
	public void enter(BaseEntity owner) {}

	@Override
	public void execute(BaseEntity owner, double deltaTime, World world) {
		PlayerBase player = (PlayerBase) owner;	
		if(player.isControllingPlayer() && player.isBallWithinReceivingRange())
			player.maxSpeed(PlayerMaxSpeedWithBall);
		else
			player.maxSpeed(PlayerMaxSpeedWithoutBall);
	}

	@Override
	public void exit(BaseEntity owner) {}

	@Override
	public boolean onMessage(BaseEntity owner, Telegram tgram) {
		PlayerBase player = (PlayerBase) owner;
		Vector2D v = null;
		switch(tgram.msg){
		case RECEIVE_BALL:
			// Get position ball was kicked to
			v = (Vector2D) tgram.extraInfo[0];
			player.targetPos.set(v);
			player.FSM().changeState(PlayerReceiveBall.state());
			break;
		case SUPPORT_ATTACKER:
			if(player.FSM().isUsingState(PlayerSupportAttacker.state()))
				return true;
			player.FSM().changeState(PlayerSupportAttacker.state());
			return true;	
		case PLAYER_PREPARE_FOR_KICKOFF:
			player.FSM().changeState(PlayerPrepareForKickOff.state());
			return true;
		case GO_TO_REGION:
			player.FSM().changeState(PlayerReturnToRegion.state());
			return true;
		case WAIT:
			player.FSM().changeState(PlayerWait.state());
			return true;
		case PASS_TO_ME:
			// Only need to consider this if the field player is within kicking distance 
//			if(player.isFieldPlayer() && player.isBallWithinKickingRange()){
			if(player.team.getReceivingPlayer() == null && player.isBallWithinKickingRange()){
				// Get the player sending this message
				FieldPlayer receiver = (FieldPlayer)tgram.extraInfo[0];
				player.team.pitch.ball.kick(player, Vector2D.sub(receiver.pos(), player.team.pitch.ball.pos()), MaxPassingForce);
				Dispatcher.dispatch(0, player.ID(), receiver.ID(), RECEIVE_BALL, receiver.pos().get());
				player.FSM().changeState(PlayerWait.state());
				player.findSupport();
			}
			return true;
		}
		return false;
	}

}
